﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;

namespace API接口示范
{
   
    public class WebHostService//主机类
    {
        private readonly IHost _host;     
        public WebHostService(int port = 8608)
        {


            _host = Host.CreateDefaultBuilder()
               .ConfigureWebHostDefaults(webBuilder =>
               {
                   webBuilder.UseUrls($"http://*:{port}");
                   webBuilder.ConfigureServices(services =>
                   {
                       services.AddControllers().AddNewtonsoftJson();
                       services.AddSwaggerGen(c =>
                       {
                           c.SwaggerDoc("v1", new OpenApiInfo { Title = "API接口示范 API", Version = "v1" });
                       });
                   });
                   webBuilder.Configure(app =>
                   {  
                       app.UseSwagger();
                       app.UseSwaggerUI(c =>
                       {
                           c.SwaggerEndpoint("/swagger/v1/swagger.json", "API接口示范 API V1");
                       });

                       app.UseRouting();
                       app.UseEndpoints(endpoints =>
                       {
                           endpoints.MapControllers();
                       });
                   });
               })
               .Build();
        }

        public void Start() => _host.Start();

        public async Task Stop()
        {
            await _host.StopAsync();
        }
    }
}
